import { apiClient } from './apiClient';
import type { 
  Position, 
  PaginatedResponse, 
  CreatePositionRequest,
  UpdatePositionRequest 
} from '@/types';

export interface GetPositionsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  departmentId?: string;
  level?: number;
  status?: 'active' | 'inactive';
  tenantId?: string;
  organizationId?: string;
}

export interface PositionBatchOperationParams {
  ids: string[];
  operation: 'delete' | 'activate' | 'deactivate' | 'move';
  targetDepartmentId?: string;
}

class PositionService {
  private baseUrl = '/api/positions';

  /**
   * 获取岗位列表
   */
  async getPositions(params: GetPositionsParams): Promise<Position[]> {
    const { data } = await apiClient.get<PaginatedResponse<Position>>(this.baseUrl, {
      params
    });
    return data.items;
  }

  /**
   * 获取岗位详情
   */
  async getPositionById(id: string): Promise<Position> {
    const { data } = await apiClient.get<Position>(`${this.baseUrl}/${id}`);
    return data;
  }

  /**
   * 创建岗位
   */
  async createPosition(position: CreatePositionRequest): Promise<Position> {
    const { data } = await apiClient.post<Position>(this.baseUrl, position);
    return data;
  }

  /**
   * 更新岗位
   */
  async updatePosition(id: string, position: UpdatePositionRequest): Promise<Position> {
    const { data } = await apiClient.put<Position>(`${this.baseUrl}/${id}`, position);
    return data;
  }

  /**
   * 删除岗位
   */
  async deletePosition(id: string): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}`);
  }

  /**
   * 批量删除岗位
   */
  async deletePositions(ids: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/batch`, {
      data: { ids }
    });
  }

  /**
   * 批量操作岗位
   */
  async batchOperation(params: PositionBatchOperationParams): Promise<void> {
    await apiClient.post(`${this.baseUrl}/batch-operation`, params);
  }

  /**
   * 获取岗位成员列表
   */
  async getPositionMembers(id: string, params?: {
    page?: number;
    pageSize?: number;
    search?: string;
  }): Promise<any[]> {
    const { data } = await apiClient.get<PaginatedResponse<any>>(`${this.baseUrl}/${id}/members`, {
      params
    });
    return data.items;
  }

  /**
   * 添加岗位成员
   */
  async addPositionMembers(id: string, userIds: string[]): Promise<void> {
    await apiClient.post(`${this.baseUrl}/${id}/members`, { userIds });
  }

  /**
   * 移除岗位成员
   */
  async removePositionMembers(id: string, userIds: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}/members`, {
      data: { userIds }
    });
  }

  /**
   * 获取岗位权限
   */
  async getPositionPermissions(id: string): Promise<string[]> {
    const { data } = await apiClient.get<string[]>(`${this.baseUrl}/${id}/permissions`);
    return data;
  }

  /**
   * 设置岗位权限
   */
  async setPositionPermissions(id: string, permissions: string[]): Promise<Position> {
    const { data } = await apiClient.put<Position>(`${this.baseUrl}/${id}/permissions`, {
      permissions
    });
    return data;
  }

  /**
   * 获取岗位数据权限
   */
  async getPositionDataPermissions(id: string): Promise<{
    scope: 'all' | 'department' | 'self' | 'custom';
    departments?: string[];
    users?: string[];
  }> {
    const { data } = await apiClient.get<{
      scope: 'all' | 'department' | 'self' | 'custom';
      departments?: string[];
      users?: string[];
    }>(`${this.baseUrl}/${id}/data-permissions`);
    return data;
  }

  /**
   * 设置岗位数据权限
   */
  async setPositionDataPermissions(id: string, dataPermissions: {
    scope: 'all' | 'department' | 'self' | 'custom';
    departments?: string[];
    users?: string[];
  }): Promise<Position> {
    const { data } = await apiClient.put<Position>(`${this.baseUrl}/${id}/data-permissions`, dataPermissions);
    return data;
  }

  /**
   * 移动岗位到新的部门
   */
  async movePosition(id: string, newDepartmentId: string): Promise<Position> {
    const { data } = await apiClient.put<Position>(`${this.baseUrl}/${id}/move`, {
      departmentId: newDepartmentId
    });
    return data;
  }

  /**
   * 获取岗位统计信息
   */
  async getPositionStats(id: string): Promise<{
    userCount: number;
    activeUserCount: number;
    inactiveUserCount: number;
    permissionCount: number;
  }> {
    const { data } = await apiClient.get<{
      userCount: number;
      activeUserCount: number;
      inactiveUserCount: number;
      permissionCount: number;
    }>(`${this.baseUrl}/${id}/stats`);
    return data;
  }

  /**
   * 验证岗位代码是否可用
   */
  async validatePositionCode(code: string, excludeId?: string): Promise<boolean> {
    const { data } = await apiClient.get<{ available: boolean }>(`${this.baseUrl}/validate-code`, {
      params: { code, excludeId }
    });
    return data.available;
  }

  /**
   * 获取岗位层级结构
   */
  async getPositionHierarchy(departmentId?: string): Promise<Position[]> {
    const { data } = await apiClient.get<Position[]>(`${this.baseUrl}/hierarchy`, {
      params: { departmentId }
    });
    return data;
  }

  /**
   * 复制岗位
   */
  async copyPosition(id: string, data: {
    name: string;
    code: string;
    departmentId?: string;
    copyPermissions?: boolean;
  }): Promise<Position> {
    const { data: result } = await apiClient.post<Position>(`${this.baseUrl}/${id}/copy`, data);
    return result;
  }

  /**
   * 导出岗位信息
   */
  async exportPositions(format: 'json' | 'csv' | 'excel' = 'json'): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/export`, {
      params: { format },
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 导入岗位信息
   */
  async importPositions(file: File): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    
    const { data } = await apiClient.post<{
      success: number;
      failed: number;
      errors: string[];
    }>(`${this.baseUrl}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }

  /**
   * 搜索岗位
   */
  async searchPositions(query: string, params?: {
    departmentId?: string;
    tenantId?: string;
    organizationId?: string;
    limit?: number;
  }): Promise<Position[]> {
    const { data } = await apiClient.get<Position[]>(`${this.baseUrl}/search`, {
      params: {
        q: query,
        ...params
      }
    });
    return data;
  }
}

export const positionService = new PositionService();